package app

import (
	// "fmt"
	// "time"
	"os"
	"path/filepath"

	"github.com/go-apibox/api"
	"github.com/go-apibox/filter"
)

func ActionTaskList(c *api.Context) interface{} {
	params := c.NewParams()
	params.AddPagination().AddOrderBy("CreateTime", "desc", []string{"CreateTime"}, false)
	params.Add("DeviceGroupId", filter.EmptyToNil(), filter.Uint32())
	params.Add("DeviceGroupName", filter.EmptyToNil(), filter.String())

	params.Add("Name", filter.EmptyToNil(), filter.String())
	params.Add("Desc", filter.EmptyToNil(), filter.String())
	params.Add("Status", filter.EmptyToNil(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	list := make([]*Task, 0, 10)
	return api.List(c, &list, params, nil)
	// return api.ListJoin(c, &list, params, map[string]string{
	// 	"DeviceGroupName": "table:device_group",
	// 	"Name":            "like",
	// 	"Desc":            "like",
	// },
	// 	[][]string{
	// 		[]string{"INNER", "device_group", "device_group.device_group_id=task.device_group_id"},
	// 	},
	// )
}

func ActionTaskCreate(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceGroupId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	params.Add("ProductPath", filter.EmptyToNil(), filter.Required(), filter.String())
	params.Add("Name", filter.EmptyToNil(), filter.String())
	params.Add("Desc", filter.EmptyToNil(), filter.String())
	params.Add("TaskConfigId", filter.EmptyToNil(), filter.Uint32())
	params.Add("Config", filter.EmptyToNil(), filter.String())

	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	// 查询分组是否存证
	dgId := params.GetUint32("DeviceGroupId")
	dg := new(DeviceGroup)
	has, err := app.engine.Where("device_group_id=?", dgId).Get(dg)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "DeviceGroupId")
	}
	if !has {
		return c.Error.New(api.ErrorInvalidParam, "DeviceGroupId")
	}
	params.Set("DeviceGroupName", dg.DeviceGroupName)
	params.Set("Status", TASK_STATUS_UNDO)

	path := params.GetString("ProductPath")
	if _, err := os.Stat(filepath.Join(app.config.DataDir, path)); err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "ProductPath")
	}

	task := new(Task)
	data := api.Create(c, task, params)
	if !api.IsError(data) {
		err := importProduct(task)
		if err != nil {
			app.logger.Error(err)
		}
	}
	return data
}

func ActionTaskDetail(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("TaskId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}
	return api.Detail(c, new(Task), params)
}

func ActionTaskDelete(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("TaskId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	return api.Delete(c, new(Task), params)
}
